package com.lj.demo.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lj.demo.eduservice.entity.EduChapter;
import com.lj.demo.eduservice.entity.EduVideo;
import com.lj.demo.eduservice.entity.vo.ChapterVo;
import com.lj.demo.eduservice.entity.vo.VideoVo;
import com.lj.demo.eduservice.mapper.EduChapterMapper;
import com.lj.demo.eduservice.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lj.demo.eduservice.service.EduVideoService;
import com.lj.demo.servicebase.exception.AException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author liujiang
 * @since 2020-12-03
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Autowired
    private EduVideoService eduVideoService;
    @Override
    public List<ChapterVo> findChapterById(String courseId) {

        //查询章节信息，按sort升序
        QueryWrapper<EduChapter> queryWrapper = new QueryWrapper();
        queryWrapper.eq("course_id",courseId);
        queryWrapper.orderByAsc("sort","id");
        List<EduChapter> eduChapterList = baseMapper.selectList(queryWrapper);

        //查询小节信息，
        QueryWrapper<EduVideo> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("course_id",courseId);
        queryWrapper1.orderByAsc("sort","id");
        List<EduVideo> eduVideoList = eduVideoService.list(queryWrapper1);

        //创建最终返回的ChapterVo集合
        List<ChapterVo> chapterVos = new ArrayList<>();
        //填充章节vo数据
        for (int i = 0; i < eduChapterList.size(); i++) {
            EduChapter eduChapter = eduChapterList.get(i);
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(eduChapter,chapterVo);


            List<VideoVo> videoVos = new ArrayList<>();
            for (int m = 0; m < eduVideoList.size(); m++) {
                EduVideo eduVideo = eduVideoList.get(m);
                VideoVo videoVo = new VideoVo();
                BeanUtils.copyProperties(eduVideo, videoVo);
                if(eduChapter.getId().equals(eduVideo.getChapterId())){
                    videoVos.add(videoVo);
                    chapterVo.setChildren(videoVos);
                }
            }
            chapterVos.add(chapterVo);
        }
            return chapterVos;
    }

    //根据id删除章节
    @Override
    public boolean deleteById(String id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("chapter_id",id);
        int count = eduVideoService.count(queryWrapper);
        if (count == 0){
            int i = baseMapper.deleteById(id);
            return i>0;
        }else {
            throw new AException(20001,"章节中有小节信息，不能删除");
        }

    }
}
